/**
 * @(#)SeachDataController.java 2017年6月2日
 * Copyright(C) 2017年6月2日 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.domian.NewExecutionGroup;
import org.jsbd.boss.domian.NewExecutionGroupMark;
import org.jsbd.boss.domian.NewExecutionGroupMarkVO;
import org.jsbd.boss.domian.channel.ChannelApkConfig;
import org.jsbd.boss.domian.channel.NewExecutionGroupMarkDto;
import org.jsbd.boss.service.IDaylimitService;
import org.jsbd.boss.service.INewExecutionGroupService;
import org.jsbd.boss.util.BigDecimalUtil;
import org.jsbd.boss.util.DateUtil;
import org.jsbd.boss.util.NumUtil;
import org.jsbd.boss.util.SortList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 新增执行分组查询
 * 
 * @author <a href="mailto:zhouchao@zhexinit.com" >王俊标</a>
 * @version 1.0.0
 */
@Controller
@RequestMapping("/new/execution")
public class NewExecutionGroupController {
	public static final Logger LOGGER = LoggerFactory.getLogger(NewExecutionGroupController.class);

	@Autowired
	private INewExecutionGroupService newExecutionGroupService;

	/**
	 * 分组列表页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/groupList")
	public String groupList() throws Exception {
		return "newExecution/groupList";
	}

	/**
	 * 分组数据
	 * 
	 * @param page
	 *            分页信息
	 * @param billSearchModel
	 *            查询条件
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/grouplistJson")
	@ResponseBody
	public Map<String, Object> groupListJson(DataGridModel page, NewExecutionGroupMarkDto dto) throws Exception {
		return newExecutionGroupService.getGroupListWithPage(page, dto);
	}

	/**
	 * 分组关联的mark数据
	 * 
	 * @param model
	 * @param groupId
	 *            分组ID
	 * @return
	 */
	@RequestMapping(value = "/getGroupDetail")
	public String getGroupDetail(Model model, Integer groupId) {
		List<NewExecutionGroupMark> list = newExecutionGroupService.getGroupDetailById(groupId);
		model.addAttribute("list", list);
		return "newExecution/groupDetail";
	}

	/**
	 * 跳转新增分组页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String toAddGroup() {
		return "newExecution/groupAdd";
	}

	/**
	 * 新增分组
	 * 
	 * @param newExecutionGroup
	 *            分组实体
	 * @param response
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public void addGroup(NewExecutionGroup newExecutionGroup, HttpServletResponse response) {
		try {
			newExecutionGroupService.addGroup(newExecutionGroup);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	/**
	 * 跳转编辑账单页面
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	public String toEditGroup(Model model, @PathVariable Integer id) {
		NewExecutionGroup neg = newExecutionGroupService.getGroupById(id);
		model.addAttribute("neg", neg);
		return "newExecution/groupEdit";
	}

	/**
	 * 编辑账单
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.POST)
	@ResponseBody
	public void editGroup(Model model, @PathVariable Integer id, NewExecutionGroup newExecutionGroup, HttpServletResponse response) {
		try {
			newExecutionGroup.setId(id);
			newExecutionGroupService.updateGroup(newExecutionGroup);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	/**
	 * 删除分组
	 * 
	 * @param model
	 * @param id
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete")
	@ResponseBody
	public void deleteGroup(Model model, @PathVariable Integer id, HttpServletResponse response) {
		try {
			List<NewExecutionGroupMark> groupMarks = newExecutionGroupService.getGroupMarkById(id);
			if (null != groupMarks && groupMarks.size() > 0) {
				ResponseUtils.responseHasRefMarks(response);
			} else {
				newExecutionGroupService.deleteGroup(id);
				ResponseUtils.responseSuccess(response);
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	/**
	 * 跳转新增关联Mark页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/addMark", method = RequestMethod.GET)
	public String toAddMark(Model model, @PathVariable Integer id) {
		model.addAttribute("groupId", id);
		return "newExecution/groupMarkAdd";
	}

	/**
	 * 关联Mark
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}/addMark", method = RequestMethod.POST)
	@ResponseBody
	public void addMark(Model model, @PathVariable Integer id, String mark, HttpServletResponse response) {
		try {
			ChannelApkConfig channelApkConfig = newExecutionGroupService.getApkByMark(mark);
			NewExecutionGroupMark negr = newExecutionGroupService.getMarkByGroupIdAndMark(id, mark);
			if (null == channelApkConfig) {
				ResponseUtils.responseMarkNotExists(response);
			} else if (null != negr) {
				ResponseUtils.responseMarkExists(response);
			} 
			else {
				NewExecutionGroupMark newExecutionGroupMark = new NewExecutionGroupMark();
				newExecutionGroupMark.setGroupId(id);
				newExecutionGroupMark.setMark(mark);
				newExecutionGroupMark.setApkName(channelApkConfig.getApkName());

				newExecutionGroupService.addGroupMark(newExecutionGroupMark);
				ResponseUtils.responseSuccess(response);
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	/**
	 * 删除关联的Mark
	 * 
	 * @param model
	 * @param id
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/{id}/deleteGroupMark")
	public void delGroupMark(Model model, @PathVariable Integer id, HttpServletResponse response) {
		try {
			newExecutionGroupService.deleteGroupMark(id);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	/**
	 * 查询分组新增量页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/searchList")
	public String searchList() {
		return "newExecution/searchList";
	}

	/**
	 * 查询分组汇总数据
	 * 
	 * @param page
	 * @param newExecutionGroup
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/searchlistJson")
	@ResponseBody
	public Map<String, Object> searchListJson(DataGridModel page, NewExecutionGroupMarkDto dto) throws Exception {
		//分组信息
		Map<String, Object> groupMap = newExecutionGroupService.getGroupListWithPage(page, dto);
		Map<String, Object> results = new HashMap<String, Object>();
		results.put("total", groupMap.get("total"));
		List<NewExecutionGroupMarkVO> rows = new ArrayList<NewExecutionGroupMarkVO>();
		List<NewExecutionGroup> groups = (List<NewExecutionGroup>) groupMap.get("rows");
		
		//默认当月
		String start = dto.getStart();
		String end = dto.getEnd();
		if (StringUtils.isBlank(start)) {
			dto.setStart(DateUtil.getY_M_DStr().substring(0, 7));
		}
		if (StringUtils.isBlank(end)) {
			dto.setEnd(DateUtil.getY_M_DStr().substring(0, 7));
		}
		
		//取新增执行量数据
		for (int i = 0; i < groups.size(); i++) {
			NewExecutionGroup ng = groups.get(i);
			Integer groupId = ng.getId();
			String groupName = ng.getGroupName();
			List<NewExecutionGroupMark> groupMarks = newExecutionGroupService.getGroupMarkById(groupId);
			List<NewExecutionGroupMarkVO> list = new ArrayList<NewExecutionGroupMarkVO>();
			if (groupMarks.size()>0) {
				dto.setMarks(groupMarks);
				dto.setGroupName(groupName);
				dto.setGroupId(groupId);
				list = newExecutionGroupService.getSearchDataTotalByGroupId(dto);
			}
			
			if (list == null || list.size()==0) {
				NewExecutionGroupMarkVO negmVO = new NewExecutionGroupMarkVO();
				negmVO.setGroupId(groupId);
				negmVO.setGroupName(groupName);
				list.add(negmVO);
			}
			rows.addAll(list);
		}
		
		String sort = dto.getSort();
		String order = dto.getOrder();
		if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
			if ("executeRate".equals(sort)) {
				SortList<NewExecutionGroupMarkVO> sortList = new SortList<NewExecutionGroupMarkVO>();  
				sortList.Sort(rows, "getExecuteRate", order);  
			}
			if ("phoneRate".equals(sort)) {
				SortList<NewExecutionGroupMarkVO> sortList = new SortList<NewExecutionGroupMarkVO>();  
				sortList.Sort(rows, "getPhoneRate", order);  
			}
			if ("payRate".equals(sort)) {
				SortList<NewExecutionGroupMarkVO> sortList = new SortList<NewExecutionGroupMarkVO>();  
				sortList.Sort(rows, "getPayRate", order);  
			}
		}
		
		results.put("rows", rows);
		return results;
	}

	/**
	 * 查询数据
	 * 
	 * @param model
	 * @param groupId
	 *            分组ID
	 * @return
	 */
	@RequestMapping(value = "/getSearchData")
	public String getSearchData(Model model, NewExecutionGroupMarkDto negmDto) {
		List<NewExecutionGroupMark> groupMarks = newExecutionGroupService.getGroupMarkById(negmDto.getGroupId());
		negmDto.setMarks(groupMarks);

		String start = negmDto.getStart();
		String end = negmDto.getEnd();
		if (StringUtils.isBlank(start)) {
			negmDto.setStart(DateUtil.getY_M_DStr().substring(0, 7));
		}
		if (StringUtils.isBlank(end)) {
			negmDto.setEnd(DateUtil.getY_M_DStr().substring(0, 7));
		}

		List<NewExecutionGroupMarkVO> list = newExecutionGroupService.getSearchDataByGroupId(negmDto);

		model.addAttribute("list", list);
		return "newExecution/searchData";
	}

}
